package com.fly.toolbox.service.impl;

import com.fly.toolbox.bean.TaskInfo;
import com.fly.toolbox.config.ApplicationProperties;
import com.fly.toolbox.constant.BankEnum;
import com.fly.toolbox.service.NoteFileService;
import com.fly.toolbox.util.DateUtils;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.text.CharSequenceReader;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NoteFileServiceImpl implements NoteFileService {

    private final ApplicationProperties instance = ApplicationProperties.getInstance();

    public void writeVersionLog(VirtualFile file, Project project, TaskInfo taskInfo) {
        saveRecentTaskInfo(taskInfo);
        Document document = FileDocumentManager.getInstance().getDocument(file);
        if (document != null) {
            ApplicationManager.getApplication().invokeLater(() -> {
                WriteCommandAction.runWriteCommandAction(project, () -> {
                    StringBuilder content = new StringBuilder();
                    String preVersion = null;
                    String newVersion = null;
                    String newLine = "";
                    try (BufferedReader reader = new BufferedReader(new CharSequenceReader(document.getCharsSequence()))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            if (file.getName().endsWith(".java")) {
                                // 使用正则表达式截取版本号
                                Matcher matcher = Pattern.compile("\\V([0-9.]+)").matcher(line);
                                if (matcher.find()) {
                                    preVersion = matcher.group(0);
                                }
                                // 生成日志
                                if (line.matches(".*\\*{4}/.*")) {
                                    if (StringUtils.isNotEmpty(preVersion)) {
                                        String prefix = preVersion.substring(0, preVersion.lastIndexOf(".") + 1);
                                        int version = Integer.parseInt(preVersion.substring(preVersion.lastIndexOf(".") + 1));
                                        newVersion = prefix + (version + 1);
                                    }

                                    newLine = generateVersionLog(taskInfo, newVersion);
                                    content.append(" * ").append(newLine).append("\n");
                                }
                                // 修改文件版本
                                if (StringUtils.isNotEmpty(newVersion)) {
                                    if (line.contains("HUNDSUN_VERSION")) {
                                        String hundsunVersion = "\tpublic static final String HUNDSUN_VERSION = \"@system 综合理财平台 @version %s @sp_version %s @lastModiDate %s @describe %s\";";
                                        line = String.format(hundsunVersion, newVersion.substring(1), taskInfo.getVersion(), DateUtils.getDate(), instance.getUser());
                                    }
                                }
                                // 修改标记
                                line = replaceMarkLog(line, newLine);
                                content.append(line).append("\n");
                            } else if (file.getName().endsWith(".jsp")) {
                                // 修改项目版本
                                if (line.trim().startsWith("@sp_version")) {
                                    if (StringUtils.isNotEmpty(taskInfo.getVersion())) {
                                        line = "\t@sp_version " + taskInfo.getVersion();
                                    }
                                }
                                // 修改文件版本
                                if (line.trim().startsWith("@version")) {
                                    preVersion = line.substring(line.indexOf("@version") + 8).trim();
                                    if (StringUtils.isNotEmpty(preVersion)) {
                                        String prefix = preVersion.substring(0, preVersion.lastIndexOf(".") + 1);
                                        int version = Integer.parseInt(preVersion.substring(preVersion.lastIndexOf(".") + 1));
                                        newVersion = prefix + (version + 1);
                                    }
                                    if (StringUtils.isNotEmpty(newVersion)) {
                                        line = "\t@version " + newVersion;
                                    }
                                }
                                // 修改标记
                                line = replaceMarkLog(line, newLine);
                                content.append(line).append("\n");
                                // 生成日志
                                if (StringUtils.isNotEmpty(preVersion) && line.trim().startsWith("V" + preVersion)) {
                                    newLine = generateVersionLog(taskInfo, "V" + newVersion);
                                    content.append("\t").append(newLine).append("\n");
                                }
                            } else if (file.getName().endsWith(".sql")) {
                                // 生成日志
                                if (line.trim().startsWith("commit;")) {
                                    StringBuilder log = new StringBuilder();
                                    log.append(DateUtils.getDate()).append("-01").append("\t").append(instance.getUser()).append("\t").append(taskInfo.getTaskId()).append("\t").append(taskInfo.getVersion()).append("\t").append(taskInfo.getMessage());
                                    String begStr = "/* " + log.toString() + " beg */";
                                    String endStr = "/* " + log.toString() + " end */";
                                    content.append(begStr);
                                    content.append("\n");
                                    content.append(endStr);
                                    content.append("\n");
                                }
                                content.append(line).append("\n");
                            }
                        }
                        document.setText(content);
                    } catch (IOException e) {
                        // 处理异常
                    }
                });
            });
        }
    }

    private String replaceMarkLog(String line, String newLine) {
        if (StringUtils.isEmpty(line) || StringUtils.isEmpty(newLine)) {
            return line;
        }
        String begin = instance.getUser() + " beg";
        String end = instance.getUser() + " end";
        if (line.trim().startsWith("//") || line.trim().startsWith("/*") || line.trim().startsWith("<!--") || line.trim().startsWith("<%--")) {
            if (line.contains(begin)) {
                line = line.replaceAll(begin, newLine + " beg");
            }
            if (line.contains(end)) {
                line = line.replaceAll(end, newLine + " end");
            }
        }
        return line;
    }

    private void saveRecentTaskInfo(TaskInfo taskInfo) {
        ApplicationProperties.getInstance().addHistory(generateSvnLog(taskInfo), taskInfo);
    }

    public String generateVersionLog(TaskInfo taskInfo, String fileVersion) {
        String sysDate = DateUtils.getDate();
        if (fileVersion == null) {
            fileVersion = "V5.0.0.1";
        }
        return fileVersion + " " + sysDate + "-01" + "\t" + instance.getUser() + "\t" + taskInfo.getTaskId() + "\t" + taskInfo.getVersion() + "\t" + taskInfo.getMessage();
    }

    @Override
    public TaskInfo parseTaskInfo(String text, String version) {
        if (StringUtils.isEmpty(text)) {
            return null;
        }
        TaskInfo taskInfo = new TaskInfo();
        if (StringUtils.isNotEmpty(version)) {
            taskInfo.setVersion(version);
        }
        Arrays.stream(text.split("\n")).forEach(str -> {
            str = str.trim();
            str = str.replaceAll("\\s", "");
            if (str.startsWith("[修改单编号]") || str.startsWith("T")) {
                str = str.replaceAll("\\[修改单编号]", "");
                taskInfo.setTaskId(str);
            } else if (str.startsWith("[需求描述]") || str.startsWith("「开发」") || str.startsWith("【缺陷")) {
                str = str.replaceAll("\\[需求描述]", "");
                if (str.indexOf("】") > 0) {
                    str = str.substring(str.indexOf("】") + 1);
                }
                taskInfo.setMessage(str.replaceAll("「开发」", ""));
            } else if (str.startsWith("[需求编号]") || str.matches("^20\\d{2}.*")) {
                str = str.replaceAll("\\[需求编号]", "");
                taskInfo.setOrderId(str);
            } else if (str.startsWith("[需求引入行]") || str.contains("理财") || str.contains("商行") || str.contains("内部客户") || str.contains("银行(")) {
                str = str.replaceAll("\\[需求引入行]", "");
                taskInfo.setBankName(str);
                taskInfo.setBankAlias(BankEnum.parseBankAlias(str));
            } else if (str.startsWith("[所属版本]") || str.startsWith("BTA5.0V20")) {
                str = str.replaceAll("\\[所属版本]", "");
                taskInfo.setVersion(str);
            }
        });

        return taskInfo;
    }

    @Override
    public String generateSvnLog(TaskInfo taskInfo) {
        if (taskInfo != null) {
            return "[需求编号]" + taskInfo.getOrderId() + "\n" +
                    "[需求引入行]" + taskInfo.getBankName() + "\n" +
                    "[需求描述]" + taskInfo.getMessage() + "\n" +
                    "[修改单编号]" + taskInfo.getTaskId() + "\n" +
                    "[所属版本]" + taskInfo.getVersion();
        }
        return "";
    }
}
